package com.SilenceEcho.tool;

import com.SilenceEcho.mapper.JgwMapper;
import com.SilenceEcho.pojo.Jgw;
import com.SilenceEcho.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;


import java.net.URL;
import java.net.URLConnection;
import java.time.Duration;
import java.util.List;

import java.io.*;



public class Demo {
    public static void main(String[] args) throws IOException {

        SqlSession session;
        session= MybatisUtils.getSqlSession();
        JgwMapper jgwMapper=session.getMapper(JgwMapper.class);


        String bjh="002";

        int zh=0;

        //edge驱动
        EdgeOptions options = new EdgeOptions();

        //允许所有请求
        options.addArguments("--remote-allow-origin=*");
        WebDriver webDriver = new EdgeDriver(options);

        //打开网站
        webDriver.get("http://jgw.aynu.edu.cn/home/zx/index.html");
        webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        String mainWindowHandle = webDriver.getWindowHandle();
        //由于有重复打开一个网页，因此网站会弹出广告从而阻塞了程序的运行，故给点时间下脚本（doge
        try {
            Thread.currentThread().sleep(60000);
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }

        //点击对应的字体
        WebElement  tu = webDriver.findElement(By.cssSelector("[data-radical='50001']"));
        tu.click();
        WebElement dragDom2 = webDriver.findElement(By.className("radical_init"));
        Wait<WebDriver> wait = new WebDriverWait(webDriver, Duration.ofSeconds(10));
        wait.until(d -> dragDom2.isDisplayed());
        try {
            webDriver.findElement(By.className("jgw_font_show"));
        } catch (Exception e) {

            try {
                Thread.currentThread().sleep(5000);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }
        WebElement jfs = webDriver.findElement(By.className("jgw_font_show"));
        wait.until(d-> jfs.isDisplayed());

        //点击对应的字
        List<WebElement> jgw = webDriver.findElements(By.className("jgw_font_show"));

        System.out.println(jgw.isEmpty());
        for (WebElement webElement : jgw) {
            //点开对应的汉典网站
            webElement.click();
            WebElement dragDom3 = webDriver.findElement(By.className("drag_dom3"));
            wait.until(d-> dragDom3.isDisplayed());

            WebElement close = webDriver.findElement(By.className("close_info"));
            WebElement hd = webDriver.findElement(By.cssSelector("[id='hdUrl']"));
            WebElement zx = webDriver.findElement(By.cssSelector("[title='可选中复制']"));

            hd.findElement(By.tagName("input")).click();
            String jgwZx=zx.getAttribute("value");

            //转换网址
            for (String handle : webDriver.getWindowHandles()) {
                if (!handle.equals(mainWindowHandle)){
                    webDriver.switchTo().window(handle);
                    zh+=1;
                    Jgw jgw1=new Jgw(bjh,zh);
                    jgw1.setZx(jgwZx);
                    if (jgwMapper.searchJGW(jgw1)!=null){
                        System.out.println("已存在 "+"编号："+zh);
                        webDriver.close();
                        break;
                    }

                    //拿到意思
                    String mean=null;
                    try {
                        WebElement xnr = webDriver.findElement(By.className("xnr"));
                        WebElement p = xnr.findElements(By.tagName("p")).get(3);
                        mean=p.getText();
                    } catch (Exception e) {
                        System.out.println("无");
                    }

                    System.out.println("意思："+mean);
                    jgw1.setZy(mean);

                    //拿到对应的表格
                    WebElement zyyb = null;
                    try {
                        zyyb = webDriver.findElement(By.className("zyyb"));
                    } catch (Exception e) {
                        webDriver.close();
                        break;

                    }
                    List<WebElement> tr = zyyb.findElements(By.tagName("tr"));
                    List<WebElement> typeface = tr.get(0).findElements(By.tagName("td"));
                    List<WebElement> img = tr.get(1).findElements(By.tagName("td"));

                    //拿到对应的字
                    String zi =webDriver.findElement(By.className("orth")).getText();
                    System.out.println(zi);
                    jgw1.setXd(zi);
                    System.out.println(img.size());
                    //获取图片url
                    for (int i=0;i<img.size();i++) {
                        String url;
                        String head;
                        try {
                            url  = img.get(i).findElement(By.className("lazy")).getAttribute("data-original");
                            head = typeface.get(i).getText();
                            System.out.println(head);
                            System.out.println(url);
                        } catch (Exception e) {
                            continue;
                        }
                        if (head.isEmpty()){
                            continue;
                        }
                        String match = jgw1.match(head);
                        System.out.println(match);
                        String imgUrl = "https:"+url;
                        download(imgUrl,zi,match);
                    }
                    System.out.println(jgwMapper.depositJGW(jgw1));
                    session.commit();
                    System.out.println();
                    webDriver.close();
                    break;
                }
            }

            webDriver.switchTo().window(mainWindowHandle);
            close.click();
        }





        session.close();
        webDriver.quit();
        System.out.println("任务完成");
    }

    public static void download(String urlString, String character, String filename) throws IOException {
        String savePath="D:\\java code\\project\\ultimately\\selenium\\src\\main\\java\\com\\SilenceEcho\\img";
        savePath+="\\"+character;
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为20s
        con.setConnectTimeout(20 * 1000);
        //文件路径不存在 则创建
        File sf = new File(savePath);
        if (!sf.exists()) {
            sf.mkdirs();
        }
        //jdk 1.7 新特性自动关闭
        try (InputStream in = con.getInputStream();
             OutputStream out = new FileOutputStream(sf.getPath() + "\\" + filename)) {
            //创建缓冲区
            byte[] buff = new byte[1024];
            int n;
            // 开始读取
            while ((n = in.read(buff)) >= 0) {
                out.write(buff, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
